package com.fafa.pos.util;

import com.fafa.pos.vo.WSResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

/**
 * Created by ZhouBing on 2017/7/21.
 *
 * 获得 webservice 的 响应值转换为WSResult
 *
 */
public class WebServiceValueCastUtil {


    public static WSResult cast(String result){

        if(result!=null && !"".equals(result.trim())){

            JSONObject rs = null;

            try {
                rs = new JSONObject(result);
                String resultCode = rs.getString("ResultCode"); //获得响应码
                Map<String,Object> resultValues = new HashMap<String,Object>();

                JSONArray jsonResultValue = rs.getJSONArray("ResultValue");
                JSONObject jsonRetValue = jsonResultValue.getJSONObject(0);
                JSONObject values = null;
                try{//正常   构造响应的信息
                    values = jsonRetValue.getJSONObject("RetValue");
                    Iterator itor = values.keys();

                    while (itor.hasNext()){
                        String key = (String)itor.next();

                        if("List".equals(key)){
                            JSONArray jsonList = values.getJSONArray("List");
                            List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
                            for(int i=0;i<jsonList.length();i++){

                                Map<String,Object> itemPropertis = new HashMap<String,Object>();

                                JSONObject item = jsonList.getJSONObject(i);

                                Iterator<String> itemItro = item.keys();
                                while (itemItro.hasNext()){
                                    String itemPropertyKey = itemItro.next();
                                    String itemPropertyValue = item.getString(itemPropertyKey);
                                    itemPropertis.put(itemPropertyKey,itemPropertyValue);
                                }

                                list.add(itemPropertis);
                            }
                            resultValues.put(key,list);

                        }else{
                            String value = values.getString(key);
                            resultValues.put(key,value);
                        }
                    }
                }catch (JSONException e) { //异常
                    resultValues.put("message",jsonRetValue.getString("RetValue"));
                }finally{
                    return new WSResult(Integer.parseInt(resultCode),resultValues);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


}
